package com.cq.base.dialog

import android.app.Dialog
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import com.cq.base.R

/**
 * 作者: CQ
 * 日期: 2021-03-29
 * 说明: 自定义等待框
 * 调用方法 LoadingDialog.Builder(this).setMessage("加载中...").setCancelable(false).setCancelOutside(false).create().show()
 */
class LoadingDialog : Dialog {
    private var mContext: Context
    constructor(context: Context) : super(context) {
        mContext = context
    }

    constructor(context: Context, themeResId: Int) : super(context, themeResId) {
        mContext = context
    }

    /**
     * 使用builder模式
     */
    class Builder {
        private var context: Context? = null
        private var message: String? = null
        private var isShowMessage = true
        private var isCancelable = false
        private var isCancelOutside = false

        constructor(context: Context) {
            this.context = context
        }

        /**
         * 设置提示信息
         *
         * @param message
         * @return
         */
        fun setMessage(message: String?): Builder {
            this.message = message
            return this
        }

        /**
         * 设置是否显示提示信息
         *
         * @param isShowMessage
         * @return
         */
        fun setShowMessage(isShowMessage: Boolean): Builder {
            this.isShowMessage = isShowMessage
            return this
        }

        /**
         * 设置是否可以按返回键取消
         *
         * @param isCancelable
         * @return
         */
        fun setCancelable(isCancelable: Boolean): Builder {
            this.isCancelable = isCancelable
            return this
        }

        /**
         * 设置是否可以取消
         *
         * @param isCancelOutside
         * @return
         */
        fun setCancelOutside(isCancelOutside: Boolean): Builder {
            this.isCancelOutside = isCancelOutside
            return this
        }

        fun create() : LoadingDialog {
            val inflater = LayoutInflater.from(context)
            val view: View = inflater.inflate(R.layout.dialog_loading, null)
            val progressBar = view.findViewById<ProgressBar>(R.id.progressBar1)
            val loadingDialog = LoadingDialog(context!!, R.style.LoadingDialog)
            val msgText = view.findViewById<TextView>(R.id.tipTextView)
            if (isShowMessage) {
                msgText.text = message
            } else {
                msgText.visibility = View.GONE
            }
            loadingDialog.setContentView(view)
            // dialog弹出后会点击屏幕或物理返回键，dialog不消失
            loadingDialog.setCancelable(isCancelable)
            // 点击Dialog以外的区域时Dialog消失
            loadingDialog.setCanceledOnTouchOutside(isCancelOutside)
            return loadingDialog
        }
    }

}